package com.matrix.geo.playmysqlgeo.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import io.netty.util.internal.ThrowableUtil;
import lombok.extern.slf4j.Slf4j;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.geojson.GeoJsonReader;
import org.locationtech.jts.io.geojson.GeoJsonWriter;

@Slf4j
public class JtsUtil {

    private static final GeoJsonReader GEO_JSON_READER = new GeoJsonReader();

    private static final GeoJsonWriter GEO_JSON_WRITER= new GeoJsonWriter();

    public static JSONObject geometry2JsonObject(Geometry geometry){
        String geoJson = GEO_JSON_WRITER.write(geometry);
        return JSON.parseObject(geoJson);
    }

    public static Geometry geoJson2Geometry(String geoJson){
        try {
            return GEO_JSON_READER.read(geoJson);
        } catch (ParseException e) {
            log.error("Fail to deserialize geoJson: " + geoJson);
            return null;
        }
    }

}
